// 创建频道名称
const LOGIN_SUCCESS_CHANNEL = 'LOGIN_SUCCESS_CHANNEL'

let broadcastChannel = null

if (window.BroadcastChannel) {
  broadcastChannel = new BroadcastChannel(LOGIN_SUCCESS_CHANNEL)
}

// 等待回调
const waitCallBack = () => {
  return new Promise((resolve) => {
    if (broadcastChannel) {
      broadcastChannel.onmessage = (event) => {
        resolve(event.data)
      }
    } else {
      window.onstorage = (e) => {
        if (e.key == LOGIN_SUCCESS_CHANNEL) {
          resolve(JSON.parse(e.newValue))
        }
      }
    }
  })
}

// 发送消息
const sendMessage = (message) => {
  if (broadcastChannel) {
    broadcastChannel.postMessage(message)
  } else {
    localStorage.setItem(LOGIN_SUCCESS_CHANNEL, message)
  }
}

// 销毁
const destroy = () => {
  if (broadcastChannel) {
    broadcastChannel.close()
    broadcastChannel = null
  } else {
    localStorage.removeItem(LOGIN_SUCCESS_CHANNEL)
  }
}

export default { waitCallBack, sendMessage, destroy }
